﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using Models;
using IService;
using Infrastructure;
using AopAlliance.Intercept;

namespace Advisor
{
    public class ExecuteRecordAdvisor : AopAlliance.Intercept.IMethodInterceptor
    {
        public object Invoke(IMethodInvocation invocation)
        {
            Stopwatch watch = Stopwatch.StartNew();
            object result = invocation.Proceed();
            watch.Stop();

            CreateExecuteRecord(invocation, watch);

            return result;
        }

        private void CreateExecuteRecord(IMethodInvocation invocation, Stopwatch watch)
        {
            string strName = invocation.Method.Name + "(";

            if (invocation.Arguments != null)
            {
                foreach (var arg in invocation.Arguments)
                {
                    strName = strName + arg.GetType().Name + ",";
                }
            }

            ExecuteRecord record = new ExecuteRecord();
            record.FunctionName = strName + ")";
            record.CostTime = watch.Elapsed.Milliseconds;
            record.CreateTime = DateTime.Now;
            record.ActionFrom = invocation.TargetType.FullName;

            IExecuteRecordService service = FactoryCreator.Create<IExecuteRecordService>();
            service.CreateRecord(record);
        }
    }
}
